package meijuli.com.join51.business.fragment;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.liaoinstan.springview.widget.SpringView;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.FlowAdapter;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.ResFlowObj;
import meijuli.com.join51.business.model.Wallet;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.LoadFooterView;
import meijuli.com.join51.business.ui.RefreshHeaderView;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;


/**
 * 流水列表页
 * @author jack
 */
public class FlowFragment extends BaseFragment {
    private static final int PAGE_SIZE = 10;
    private static final String KEY_TYPE = "key_type";
    SpringView mRefreshLayout;
    ListView mListView;
    ViewStub mViewStub;
    TextView titleRight;
    TextView mToolbarTitle;
    TextView mTextMenu;
    Toolbar mToolbar;

    private LinearLayout mEmptyView;
    private String mTitle;
    private int nowPage = 1;
    private boolean isLoadMore;
    private FlowAdapter mFlowAdapter;
    private List<ResFlowObj> mFlowObjList;

    private Call<HttpResponse<List<ResFlowObj>>> mFlowCall;
    private int type;
    private View mContentView;
    private String mDate;
    private boolean mIsLoading = false;

    public static FlowFragment newInstance(int type) {
        FlowFragment fragment = new FlowFragment();
        Bundle args = new Bundle();
        args.putSerializable(KEY_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_flow, container, false);
        return mContentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mListView = view.findViewById(R.id.lv_order);
        mViewStub = view.findViewById(R.id.view_stub);
        titleRight = view.findViewById(R.id.title_right);
        mToolbarTitle = view.findViewById(R.id.toolbar_title);
        mTextMenu = view.findViewById(R.id.text_menu);
        mToolbar = view.findViewById(R.id.toolbar);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() == null) {
            ToastUtil.getInstance().showToast(getActivity(), "获取数据失败");
            return;
        }
        initPullListView();
        showLoadingDialog();
        type = getArguments().getInt(KEY_TYPE);
        switch (type) {
            case Wallet.TYPE_WAIT_SETTLE:
                mTitle = "待结算货款明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_SETTLE:
                mTitle = "货款明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_WAIT_SUB_RUN:
                mTitle = "待结算分润明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_SUB_RUN:
                mTitle = "分润明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_WITHDRAW:
                mTitle = "提现明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_FROZEN_SILVER:
                mTitle = "冻结银子明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_SILVER:
                mTitle = "银子明细";
                mTextMenu.setVisibility(View.VISIBLE);
                break;
            case Wallet.TYPE_FREEZE_MONEY:
                mTitle = "冻结货款明细";
                mTextMenu.setVisibility(View.GONE);
                break;
            default:

                break;
        }
        initToolBar();
        requestNetwork(type, true);
    }

    private void initPullListView() {
        mFlowObjList = new ArrayList<>();
        mFlowAdapter = new FlowAdapter(getContext(), mFlowObjList);
        mListView.setAdapter(mFlowAdapter);
        mRefreshLayout.setHeader(new RefreshHeaderView(getActivity()));
        mRefreshLayout.setFooter(new LoadFooterView(getActivity()));
        mRefreshLayout.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                if (mIsLoading) {
                    return;
                }
                isLoadMore = false;
                nowPage = 1;
                requestNetwork(type, false);
            }

            @Override
            public void onLoadmore() {
                if (mIsLoading) {
                    return;
                }
                isLoadMore = true;
                requestNetwork(type, false);
            }
        });
        mFlowAdapter.setOnItemClickListener(new FlowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //流水详情
                switchFragment(FlowFragment.this, FlowDetailFragment.newInstance(mFlowObjList.get(position), type));
            }
        });
    }

    private void initToolBar() {
        mToolbar.setTitle("");
        mTextMenu.setText("筛选");
        mToolbarTitle.setText(mTitle);
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        mTextMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePicker();
            }
        });
    }

    private void showTimePicker() {
        TimePickerView pickerView = new TimePickerView(getActivity(), TimePickerView.Type.YEAR_MONTH_DAY);
        pickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                nowPage = 1;
                @SuppressLint("SimpleDateFormat")
                Format formatter = new SimpleDateFormat("yyyy-MM-dd");
                mDate = formatter.format(date);
                requestNetwork(type, true);
            }
        });
        pickerView.show();
    }


    private void requestNetwork(int type, boolean isShowLoading) {
        if (isShowLoading) {
            showLoadingDialog();
        }
        switch (type) {
            case Wallet.TYPE_WAIT_SETTLE:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getGoodsMoneyFrozen(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_SETTLE:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getGoodsMoney(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_WAIT_SUB_RUN:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getRusSubFrozen(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_SUB_RUN:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getRunSub(nowPage, PAGE_SIZE,
                        getMap());
                break;
            case Wallet.TYPE_WITHDRAW:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getBusinessExtractFlow(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_FROZEN_SILVER:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getFrozenSilver(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_SILVER:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getSilver(nowPage,
                        PAGE_SIZE, getMap());
                break;
            case Wallet.TYPE_FREEZE_MONEY:
                mFlowCall = ApiManager.get().getApiService(ApiService.class).getFreezeMoney(nowPage,
                        PAGE_SIZE,getMap());
                break;
            default:

                break;
        }

        if (mFlowCall == null) {
            return;
        }

        HttpRequest.getRequest().autoRecycle(this).start(mFlowCall, new ResponseCallback<List<ResFlowObj>>() {

            @Override
            public void onSuccess(String url, List<ResFlowObj> data) {
                dismissDialog();
                mRefreshLayout.onFinishFreshAndLoad();
                if (isLoadMore) {
                    mFlowObjList.addAll(data);
                    mFlowAdapter.notifyDataSetChanged();
                } else {
                    mFlowObjList.clear();
                    mFlowObjList.addAll(data);
                    mFlowAdapter.notifyDataSetChanged();
                }

                if (!mFlowObjList.isEmpty()) {
                    //隐藏无数据界面
                    if (mEmptyView != null) {
                        mEmptyView.setVisibility(View.GONE);
                    }
                } else {
                    //显示无数据页面
                    if (mEmptyView != null) {
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mViewStub.inflate();
                        mEmptyView = mContentView.findViewById(R.id.empty_layout);
                    }
                }
                nowPage++;
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                mRefreshLayout.onFinishFreshAndLoad();
            }
        });
    }

    public HashMap<String, String> getMap() {
        HashMap<String, String> map = new HashMap<>();
        if (mDate != null) {
            map.put("date", mDate);
        }
        return map;
    }
}
